package org.xiaojinlong.net;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.*;

/**
 * Created by jinlong on 2015/2/13.
 */
public class UDPEchoClientTimeout {
    static final int TIMEOUT = 3000;
    static final int MAXTRIES = 5; // 最大重试次数

    public static void main(String[] args) throws IOException {
//        if (args.length != 3)
//            throw new IllegalArgumentException("参数：<服务器> <发送的消息> <端口>");
        InetAddress serverAddr = InetAddress.getLoopbackAddress();
        byte[] bytesToSend = "hello jingjing".getBytes();
        int serverPort = 5555; // Integer.parseInt(args[2]);

        DatagramSocket socket = new DatagramSocket();
        socket.setSoTimeout(TIMEOUT);

        DatagramPacket sendPacket = new DatagramPacket(bytesToSend,
                bytesToSend.length, serverAddr, serverPort);
        DatagramPacket receivePacket = new DatagramPacket(
                new byte[bytesToSend.length], bytesToSend.length);

        int tries = 0; // Packets may be lost, so we have to keep trying
        boolean receivedResponse = false;
        do {
            socket.send(sendPacket); // Send the echo string
            try {
                socket.receive(receivePacket); // Attempt echo reply reception
                if (!receivePacket.getAddress().equals(serverAddr))
                    throw new IOException("Received packet from an unknown source");
                receivedResponse = true;
            } catch (InterruptedIOException e) {
                tries++;
                System.out.format("超时，还剩%d次重连\n", MAXTRIES-tries);
            }
        } while ((!receivedResponse) && (tries < MAXTRIES));

        if (receivedResponse)
            System.out.println("收到数据[" + new String(receivePacket.getData()));
        else
            System.out.println("没有响应 -- 放弃连接");

        socket.close();
    }
}
